<template>
  <view>
    <!-- <text>小胖客服</text> -->
	    <view class="title">
	      <text>小胖客服</text>
	    </view>
    <scroll-view scroll-y="true" style="height: 700px;">
      <view v-for="message in messages" :key="message.id" class="message-container">
        <view v-if="message.consultantId !== id" class="message-received">
          <text class="message-text">{{ message.content }}</text>
        </view>
        <view v-else class="message-sent">
          <text class="message-text">{{ message.content }}</text>
        </view>
      </view>
    </scroll-view>

	<view class="input-container">
	    <input
	      type="text"
	      v-model="newMessage"
	      placeholder="输入消息"
	      @keydown.enter.prevent="sendMessage"
	    />
	    <button @click="sendMessage">发送</button>
	  </view>

  </view>
</template>

<script>
import {getInfo} from "@/api/login";
import {historyInterrogation, launchInterrogation} from "@/api/websocket/websocket";

export default {
  data() {
    return {
      interrogation: {
        id: null,
        consultantId: null,
        initiatorId: null,
        doctorId: null
      },
      messages: [],
      newMessage: '',
      ws: null,
      id: null,
      isConnected: false,
      interrogationId: null,
      doctorId: null,
      user: {}
    };
  },
  methods: {
    getUserInfo(){
      getInfo().then(res => {
        console.log(res.data)
        this.user = res.data.user
        this.id = res.data.user.userId
        console.log("用户编号"+this.id)
      })
    },
    // launchInterrogation() {
    //   setTimeout(() => {
    //     this.interrogationId = 'some-interrogation-id';
    //     this.messages = [
    //       { id: 1, content: '小胖在吗在吗？', initiatorId: 101 },
		//   { id: 101, content: '你好啊，很高兴你可以关注我，请问我有什么可以帮助你的吗？', initiatorId: 1 },
    //       // 添加更多模拟消息数据
    //     ];
    //   }, 1000);
    // },
    launchInterrogation() {
      this.interrogation.consultantId= this.user.userId
      launchInterrogation(this.interrogation).then(res => {
        this.interrogationId = res.data;

        historyInterrogation(this.interrogationId).then(res => {
          console.log("查询到的历史记录:", res.data.medicalConsultationRecordList);
          if (res.data != null) {
            this.messages = res.data.medicalConsultationRecordList || [];
          }
        });
      });
    },
    connectToWebSocket() {
      const wsUrl = `ws://localhost:19898/imserver/${this.id}`;
      this.ws = new WebSocket(wsUrl);

      this.ws.onopen = () => {
        console.log('WebSocket 连接已打开');
        this.isConnected = true;
      };

      this.ws.onclose = () => {
        console.log('WebSocket 连接已关闭');
        this.isConnected = false;
      };

      this.ws.onerror = (error) => {
        console.error('WebSocket 错误', error);
        this.isConnected = false;
      };

      this.ws.onmessage = (event) => {
        const message = JSON.parse(event.data);
        if (message.content !== undefined) {
          this.messages.push(message);
          this.$refs.scrollView.scrollTop = this.$refs.scrollView.scrollHeight; // 滚动到底部
        } else {
          console.warn('接收到的数据无效或格式错误:', event.data);
        }
      };
    },
    sendMessage() {
      if (this.newMessage.trim() === '') return;
      const now = new Date();
      const formattedTime = now.toISOString().slice(0, 19).replace('T', ' ');
      const message = {
        id: Date.now(),
        inquiryId: this.interrogationId, //患者医生聊天表编号
        sender: this.id,
        content: this.newMessage,
        sendTime: formattedTime,
        to: this.doctorId
      };
      if (this.isConnected) {
        this.messages.push(message);
        this.ws.send(JSON.stringify(message));
        this.newMessage = '';
        this.$refs.scrollView.scrollTop = this.$refs.scrollView.scrollHeight; // 滚动到底部
      } else {
        console.warn('WebSocket 连接尚未建立，消息未发送');
      }
    },
  },
  onLoad() {
    this.connectToWebSocket();
    this.launchInterrogation();
  },
  onUnload() {
    if (this.ws && this.ws.readyState === WebSocket.OPEN) {
      this.ws.close();
    }
  },
};
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  height: 100vh; /* 使容器高度充满整个视口 */
  padding: 100px;
   height: 400px; /* 直接设置按钮的高度 */
  box-sizing: border-box;
}

.title {
  text-align: center;
  margin-bottom: 20px;
}

.message-list {
  flex: 1; /* 使消息列表占据剩余空间 */
  overflow-y: auto; /* 允许垂直滚动 */
  padding: 0 10px; /* 为消息列表添加一些内边距 */
  box-sizing: border-box;
}

.message-container {
  display: flex;
  align-items: flex-start;
  margin-bottom: 15px;
}

.message-received {
  margin-right: auto;
  background-color: #e0e0e0;
  border-radius: 12px;
  padding: 12px;
  max-width: 100%;
  word-wrap: break-word;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.message-sent {
  margin-left: auto;
  background-color: #00bfff;
  color: white; /* 添加文字颜色 */
  border-radius: 12px;
  padding: 12px;
  max-width: 70%;
  word-wrap: break-word;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.message-text {
  font-size: 12px; /* 调整字体大小 */
}

.time {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.input-container {
  display: flex;
  justify-content: space-between;
  width: 100%; /* 使输入框容器宽度充满父元素 */
  box-sizing: border-box;
  padding: 10px;
  background-color: white; /* 添加背景颜色 */
  border-top: 1px solid #ddd; /* 添加顶部边框 */
  position: fixed; /* 固定输入框位置 */
  bottom: 0; /* 放置在页面底部 */
  left: 0;
  right: 0;
}

input {
  flex: 10;
  border: 1px solid #ccc; /* 非常大的边框，通常不推荐 */
  border-radius: 50px;
  padding: 10px; /* 非常大的内边距，通常不推荐 */
  font-size: 16px; /* 调整输入框字体大小 */
  height: 40px; /* 这个设置被边框和内边距覆盖，实际上不起作用 */
  margin-top: -100px; /* 使用负外边距将输入框向上移动 */
  box-sizing: border-box; /* 确保padding和border不会增加元素的总宽度和高度 */
}

button {
  border: none;
  background-color: #007aff;
  color: white;
  padding: 1px 2px;
  border-radius: 5px;
  font-size: 16px; /* 调整按钮字体大小 */
  height: 40px; /* 直接设置按钮的高度 */
  margin-top: -100px;
}

</style>
